package org.deltaset.meta.internal;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.deltaset.meta.Finder;

/**
 *
 * @author dmakariev
 */
class CollectionFinder implements Finder {

    private final Method finder;
    private final Object service;

    public CollectionFinder(final Method finder, final Object service) {
        this.finder = finder;
        this.service = service;
    }

    @Override
    public long counter(final Object... params) {
        final Collection collection = (Collection) ReflectionUtils.execute(finder, service, params);
        return collection.size();
    }

    @Override
    public List<Object> finder(final int firstResult, final int maxResult, final Object... params) {
        final Collection collection = (Collection) ReflectionUtils.execute(finder, service, params);
        final List<Object> list = new ArrayList<Object>();
        final int maxIndex = firstResult + maxResult;
        int currentIndex = 0;
        for (final Iterator it = collection.iterator(); it.hasNext();) {
            final Object object = it.next();
            if (currentIndex >= maxIndex) {
                break;
            }
            if (currentIndex >= firstResult) {
                list.add(object);
            }
            currentIndex++;
        }
        return list;
    }
}
